package com.martin.lib_base.model

import android.app.Activity
import androidx.lifecycle.MutableLiveData
import com.luck.picture.lib.entity.LocalMedia
import com.luck.picture.lib.interfaces.OnResultCallbackListener
import com.martin.lib_base.bean.UploadBean
import com.martin.lib_base.interfaces.ILoading
import com.martin.lib_base.ktx.ResultBuilder
import com.martin.lib_base.ktx.handle
import com.martin.lib_base.ktx.launchCollect
import com.martin.lib_base.ktx.launchLoadingCollect
import com.martin.lib_base.utils.MediaUtil
import com.martin.lib_base.utils.UploadUtil
import java.util.ArrayList

/**
 * @desc：单张图片选择功能
 */
class SingleImagePickModel(
    //是否需要上传
    private val needUpload: Boolean = false,
    //加载框对象,用于展示上传时的等待框
    private val iLoading: ILoading? = null,
    /**
     * 成功回调
     * {needUpload}为false时,选择图片成功即调起
     * 为true时,上传图片成功才会调起
     */
    private val successCallBack: () -> Unit = {}
) {

    //图片本地地址
    val imagePath = MutableLiveData<String>()

    //图片网络地址
    val imageUrl = MutableLiveData<String>()

    /**
     * 选择图片
     */
    fun picker(activity: Activity) {
        MediaUtil.pickImage(activity, 1) {list->
            if (!list.isNullOrEmpty()) {
                if (needUpload) {
                    //TODO 上传图片
                } else {
                    imagePath.value = list[0].realPath
                    successCallBack()
                }
            }
        }
    }

    /**
     * 上传图片
     */
    private fun uploadImage(path: String) {
        // 结果构建器
        val resultBuilder: ResultBuilder<UploadBean>.() -> Unit = {
            onSuccess = {
                imagePath.value = path
                imageUrl.value = it.data?.file
                successCallBack()
            }
        }
        // 判断是否有loading,有则使用loading,没有则使用普通的
        iLoading.handle({
            it.launchLoadingCollect({
                UploadUtil.upload(path)
            }, resultBuilder)
        }, {
            launchCollect({
                UploadUtil.upload(path)
            }, resultBuilder)
        })
    }
}